<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- el-alarm 警告区域 -->
      <el-alert
        title="添加商品信息"
        type="info"
        show-icon
        center
        :closable="false"
      ></el-alert>

      <!-- step步骤条 -->
      <el-steps :active="activeIndex - 0" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab 区域 -->
      <el-form
        :model="addGoodForm"
        :rules="addGoodFormRules"
        ref="addGoodFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="addGoodForm.goods_price"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number" type="number">
              <el-input v-model="addGoodForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addGoodForm.goods_cat"
                :options="cateList"
                :props="cascaderProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="(item, index) in manyTabData"
              :key="index"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="sub"
                  v-for="(sub, index) in item.attr_vals"
                  :key="index"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, i) in onlyTabData"
              :key="i"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addGoodForm.goods_introduce"></quill-editor>
            <el-button type="primiary" class="btnAdd" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>
<script>
var _ = require('lodash');

export default {
  data() {
    return {
      activeIndex: '0',
      addGoodForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: '',
        goods_nnmber: 0,
        goods_cat: [], // 商品分类数组
        pic: [], // 上传图片数组
        goods_introduce: ''
      }, // 表单绑定的数据对象
      addGoodFormRules: {
        // 表单验证规则对象
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' },
        ],
      },
      cateList: [], // 参数列表

      // 级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id', // 选择的属性
        label: 'cat_name', // 界面展示属性
        children: 'children',
        expandTrigger: 'hover',
      },

      manyTabData: [], // 动态参数列表
      onlyTabData: [], // 静态属性参数列表
      uploadURL: '/izhaowang/upload', // 图片上传地址
      headersObj: { // 设置upload组件的请求头
        Authorization: window.sessionStorage.getItem('token')
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取参数列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        this.$message.error('获取参数列表失败')
      }
      this.$message.success('获取参数列表成功')
      this.cateList = res.data.result
    },

    // 级联选择器改变时
    handleChange() {
      console.log(this.addGoodForm.goods_cat)
      // 级联选择器选择范围只能是三级。 二级或者一级清空数组
      if (this.addGoodForm.goods_cat.length !== 3) {
        this.addGoodForm.goods_cat = []
      }
    },

    // tab 切换时的钩子函数
    beforeTabLeave(activeName, oldActiveName) {
      // activeName 即将要进入的 tab-pane 对应的name值
      // olbActiveName 要离开的 tab-pane 对应的name值
      // return false 不会进行tab栏切换
      console.log('即将要进入的 tab-pane 对应的name值-- ' + activeName)
      console.log('要离开的 tab-pane 对应的name值-- ' + oldActiveName)
      if (oldActiveName === '0' && this.addGoodForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },

    // tab店家切换时事件
    async tabClicked() {
      console.log(this.activeIndex) // 点击tab是，tab-click会打印出 当前点击的tab-pane的name属性值
      if (this.activeIndex === '1' || this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateID}/attributes`,
          {
            params: {
              sel: 'many',
            },
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数列表失败')
        }
        this.$message.success('获取参数列表成功')
        console.log(res.data)
        if (this.activeIndex === '1') {
          res.data.forEach((item) => {
            item.attr_vals =
              item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ');
          })
          this.manyTabData = res.data
        } else {
          this.onlyTabData = res.data
        }
      }
    },

    // 处理图片预览效果
    handlePreview(file){
      console.log(file);
    },

    // 图片上传成功的操作
    handleSuccess(response) {
      const picInfo = {
        pic: response.data.tmp_path
      }
      this.addGoodForm.pic.push(picInfo);
      console.log(this.addGoodForm.pic);
    },
    
    // 处理移除图片的操作
    handleRemove(file) {
      const filePath = file.response.data.tem_path;
      const i = this.addGoodForm.pic.findIndex(item=>{
        item.pic === filePath
      });
      this.addGoodForm.pic.splice(i, 1);
    },

    // 添加商品事件
    add(){
      this.$refs.addGoodFormRef.valiate(valid=>{
        if(!valid) {
          return this.$message.error('请填写必要的表单项')
        }
        // 如果表单项验证成功就执行添加逻辑
        // 直接修改this.addGoodForm中的goods_cat 会影响级联选择器,因此需要操作goods_cat
        const form = _cloneDeep(this.addGoodForm);
        form = form.goods_cat.jion(',')
      })
      
    }
  },
  computed: {
    cateID() {
      if (this.addGoodForm.goods_cat.length === 3) {
        return this.addGoodForm.goods_cat[2]
      }
      return null
    },
  },
}
</script>
<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.btnAdd {
  margin-top: 15px;
}
</style>